<script setup lang="ts">
import { ref } from "vue";
import type { MaterialUploadParams, UserListResponse } from "@/api/material";
import { uploadMaterial } from "@/api/material";
import { ElMessage, UploadFile } from "element-plus";
import { getOSSToken } from "@/api/material";

const props = defineProps<{
  visible: boolean;
  enumOptions: {
    audioLabel: Array<{ key: string; value: string }>;
    videoLabel: Array<{ key: string; value: string }>;
  };
  directorOptions: UserListResponse["list"];
  editorOptions: UserListResponse["list"];
  adAccountsOptions: { adAccountId: number; adAccountName: string }[];
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}>();

const formRef = ref();
const uploadRef = ref();
const loading = ref(false);

const form = ref<Omit<MaterialUploadParams, "file">>({
  videoLanguage: "",
  audioLanguage: "",
  adAccountIdList: [],
  director: "",
  editor: "",
  videoMode: 1,
  name: ""
});

const fileList = ref<UploadFile[]>([]);

const rules = {
  videoLanguage: [
    { required: true, message: "请选择视频语言", trigger: "change" }
  ],
  audioLanguage: [
    { required: true, message: "请选择音频语言", trigger: "change" }
  ],
  name: [{ required: false, message: "请输入素材名称", trigger: "change" }],
  adAccountIdList: [
    { required: false, message: "请选择广告账户ID", trigger: "change" }
  ],
  director: [{ required: true, message: "请选择编导", trigger: "change" }],
  editor: [{ required: true, message: "请选择剪辑师", trigger: "change" }],
  videoMode: [{ required: true, message: "请选择视频模式", trigger: "change" }]
};

const handleClose = () => {
  emit("update:visible", false);
  formRef.value?.resetFields();
  fileList.value = [];
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (fileList.value.length === 0) {
        ElMessage.error("请上传视频文件");
        return;
      }

      try {
        loading.value = true;
        // 1. 获取 OSS 上传凭证
        const ossToken = await getOSSToken();

        // 2. 使用 Promise.all 并行上传所有文件到 OSS
        const ossUrls = await Promise.all(
          fileList.value.map(async file => {
            const formData = new FormData();
            formData.append("key", `${ossToken.dir}/${file.name}`);
            formData.append("policy", ossToken.policy);
            formData.append("OSSAccessKeyId", ossToken.accessid);
            formData.append("success_action_status", "200");
            formData.append("signature", ossToken.signature);
            formData.append("file", file.raw);

            // 上传到 OSS
            await fetch(ossToken.host, {
              method: "POST",
              body: formData
            });

            // 返回文件的 OSS URL
            return `${ossToken.host}/${ossToken.dir}/${file.name}`;
          })
        );
        console.log(ossUrls, "ossUrlsossUrls");
        // 3. 调用素材上传接口
        // await Promise.all(
        //   fileList.value.map(async (file, index) => {

        const params: any = {
          ...form.value,
          ossUrlList: ossUrls
          // name:
          //   ossUrls.length > 1
          //     ? `${form.value.name}_${ossUrls.length}`
          //     : form.value.name
        };
        if (form.value.name) {
          params.name = params.name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9_-]/g, "");
        } else {
          delete params.name;
        }
        await uploadMaterial(params);
        //   })
        // );

        ElMessage.success("上传成功");
        handleClose();
        emit("success");
      } catch (error) {
        console.error("上传失败:", error);
        ElMessage.error("上传失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleExceed = () => {
  ElMessage.warning("最多只能上传5个视频文件");
};

const beforeUpload = (file: File) => {
  const isVideo = file.type.startsWith("video/");
  if (!isVideo) {
    ElMessage.error("只能上传视频文件");
    return false;
  }
  return true;
};

const handleChange = (file: UploadFile, files: UploadFile[]) => {
  fileList.value = files;
  // 如果是第一个文件，用它的名字作为默认素材名称
  // if (files.length === 1) {
  //   form.value.name = file.name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9_-]/g, "");
  // } else if (files.length > 1) {
  //   // 多个文件时，清空默认名称
  //   form.value.name = "";
  // }
};
</script>

<template>
  <el-dialog
    title="上传素材"
    :model-value="visible"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @update:model-value="val => emit('update:visible', val)"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="视频语言" prop="videoLanguage">
        <el-select
          v-model="form.videoLanguage"
          placeholder="请选择视频语言"
          class="w-full"
        >
          <el-option
            v-for="item in props.enumOptions.videoLabel"
            :key="item.value"
            :label="item.key"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="音频语言" prop="audioLanguage">
        <el-select
          v-model="form.audioLanguage"
          placeholder="请选择音频语言"
          class="w-full"
        >
          <el-option
            v-for="item in props.enumOptions.audioLabel"
            :key="item.value"
            :label="item.key"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="素材名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入素材名称" />
      </el-form-item>
      <el-form-item label="视频模式" prop="videoMode">
        <el-radio-group v-model="form.videoMode">
          <el-radio :label="1">竖版</el-radio>
          <el-radio :label="2">横版</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="adAccountIdList" label="广告账户">
        <el-select
          v-model="form.adAccountIdList"
          placeholder="请选择广告账户"
          clearable
          multiple
          collapse-tags
          class="!w-[220px]"
        >
          <el-option
            v-for="item in props.adAccountsOptions"
            :key="item.adAccountId"
            :label="item.adAccountName"
            :value="item.adAccountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="director" label="编导">
        <el-select
          v-model="form.director"
          placeholder="请选择编导"
          clearable
          filterable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in props.directorOptions"
            :key="item.accountId"
            :label="item.nickName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="editor" label="剪辑">
        <el-select
          v-model="form.editor"
          placeholder="请选择剪辑"
          clearable
          filterable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in props.editorOptions"
            :key="item.accountId"
            :label="item.nickName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="视频文件">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :limit="5"
          multiple
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :file-list="fileList"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">只能上传视频文件</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.upload-demo {
  width: 100%;
}
</style>
